import { TApiListRequest } from "@/api/Modules/HttpRequest";
import { ElPagination } from "element-plus";
import { reactive, ref, Ref, toRefs } from "vue";
type IConfig<T> = {
	apiFunction: (params?: any) => TApiListRequest<T>;
	paginationConfig?: InstanceType<typeof ElPagination>["$props"];
	dataFields?: string;
};
type useElPagination = <T>(config: IConfig<T>) => {
	searchModel: Ref<{
		pageNum: number;
		pageSize: number;
	}>;
	dataSource: Ref<T[]>;
	Pagination: () => JSX.Element;
	loadData: (otherParams?: any) => Promise<void>;
	handleRefresh: (otherParams?: any) => Promise<void>;
	loadingStatus: Ref<boolean>;
};
interface IState {
	searchModel: {
		pageNum: number;
		pageSize: number;
	};
	dataSource: any;
	total: number;
	loadingStatus: boolean;
}

/**
 * 通用分页hooks
 * @returns
 */
export const useElPagination: useElPagination = (config) => {
	const state = reactive<IState>({
		searchModel: {
			pageNum: 1,
			pageSize: 10
		},
		dataSource: [],
		total: 10,
		loadingStatus: false
	});
	/** 刷新 */
	const handleRefresh = async (otherParams: any) => {
		state.searchModel.pageNum = 1;
		await loadData(otherParams);
	};
	/**
	 * 加载数据
	 * @param otherParams
	 * @returns
	 */
	const loadData = async (otherParams?: any) => {
		state.loadingStatus = true;
		let result = await config.apiFunction({ ...state.searchModel, ...otherParams });
		state.dataSource = result[config.dataFields || "rows"];
		state.total = result.total;
		state.loadingStatus = false;
	};
	const Pagination = () => {
		return (
			<ElPagination
				page-sizes={[10, 20, 30, 40, 50, 100]}
				total={state.total}
				v-model:current-page={state.searchModel.pageNum}
				v-model:page-size={state.searchModel.pageSize}
				layout="total, sizes, prev, pager, next, jumper"
				background
				onCurrent-change={async (value) => {
					state.searchModel.pageNum = value;
					await loadData();
				}}
				onSize-change={async (value) => {
					state.searchModel.pageNum = 1;
					state.searchModel.pageSize = value;
					await loadData();
				}}
				{...config.paginationConfig}
			/>
		);
	};
	return {
		loadData,
		Pagination,
		...toRefs(state),
		handleRefresh
	};
};
